/**
 * Created by Administrator on 2017/7/20.
 */
(function() {
    "use strict";
    var app = angular.module("angularApp");
    app.controller('iconCtrl', function ($scope,$rootScope, $http,$uibModal,fac,$timeout) {
        $scope.search = {};
        $scope.iconTypes=$.extend([],$rootScope.iconTypeEnum,true);
      /*  $(document).on("resize","#iconScroll",function(){
            $(this).css("height",window.height-180);
        })*/
       /* $scope.find = function(pageNo){
            if($scope.curType){
                $scope.search.typeId = $scope.curType.id;
                $.extend($scope.search,{currentPage:pageNo||$scope.curType.pageModel.currentPage||1,pageSize:$scope.curType.pageModel.pageSize||20000});
                fac.getPageResult("../icon/list",$scope.search,function(data){
                    $scope.curType.pageModel = data;
                    $("#iconScroll").css("height",window.innerHeight-190);
                });
            }
        };*/

        function find (pageNo,iconType){
            var params = {typeId:iconType.id};
            if($scope.curType){
                $scope.search.folderId = $scope.curType.id;
                $.extend(params,$scope.search,{currentPage:pageNo||iconType.pageModel.currentPage||1,pageSize:iconType.pageModel.pageSize||20000});
                fac.getPageResult("../icon/list",params,function(data){
                    iconType.pageModel = data;
                    $(".iconScroll").css("height",window.innerHeight-190);
                });
            }
        };

        $scope.findImage = function(pageNo){
            find(pageNo,$scope.iconTypes[0]);
        }
        $scope.findSprite = function(pageNo){
            find(pageNo,$scope.iconTypes[1]);
        }


        $http.get("../icon/listIconType").success(function(resp){
            if(resp.code === 0){
                $scope.typeList = resp.data;
                $scope.typeList.length && ($scope.selectType($scope.typeList[0]));
                $("#folderScroll").css("height",window.innerHeight-90);
            }else{
                alert(resp.msg);
            }
        })
        // icons.unshift(0,0);
       //  picList.splice.apply(picList,icons);
        $scope.addPhotos = function (params) {
            fac.upload({ url: "/icon/uploadImg" ,multiple:true,params:params,accept:"image/png" }, function (resp) {
                if (resp.code == 0 ) {
                    var icons = resp.data.icons;
                    var  deleteIds = resp.data.deleteIds;
                    var message = "成功上传"+icons.length+"张图片！";
                    if(deleteIds && deleteIds.length){
                        message +="共"+deleteIds.length+"张图标被替换！"
                    }
                    icons.forEach(function(icon){
                        var pageModel = $scope.iconTypes[0].pageModel;
                        if(icon.iconType == 2){
                            pageModel = $scope.iconTypes[1].pageModel;
                        }
                        var toDel = pageModel.data.find(function(m){return m.name == icon.name});
                        if(toDel){
                            pageModel.data.splice(pageModel.data.indexOf(toDel),1);
                            pageModel.totalRecord --;
                        }
                        pageModel.data.splice(0,0,icon);
                        pageModel.totalRecord ++;
                    })
                    msg(message)
                    $scope.$apply();
                }else{
                    alert(resp.msg);
                }
            })
        }
        $scope.delAll = function(){
            var ids = $scope.iconTypes[0].pageModel.list.reduce(function (ret, n) {
                n.checked && ret.push(n.id);
                return ret
            }, []);
            $scope.iconTypes[1].pageModel.list.reduce(function (ret, n) {
                n.checked && ret.push(n.id);
                return ret
            }, ids);
            confirm("确认删除选中的 " + ids.length + " 个图标吗?",function(){
                $http.post("../icon/del", {
                    "ids": ids.join()
                }, fac.postConfig).success(function (resp) {
                    if (resp.code == 0) {
                        ids.forEach(function(id){
                            var toDel = $scope.iconTypes[0].pageModel.list.find(function(m){return m.id == id});
                            if(toDel){
                                $scope.iconTypes[0].pageModel.list.splice($scope.iconTypes[0].pageModel.list.indexOf(toDel),1);
                                $scope.iconTypes[0].pageModel.totalRecord --;
                            }else{
                                toDel = $scope.iconTypes[1].pageModel.list.find(function(m){return m.id == id});
                                if(toDel){
                                    $scope.iconTypes[1].pageModel.list.splice($scope.iconTypes[1].pageModel.list.indexOf(toDel),1);
                                    $scope.iconTypes[1].pageModel.totalRecord --;
                                }
                            }
                        })
                    } else {
                        alert(resp.msg);
                    }
                })
            })
        }

        $scope.downloadZip = function(){
            var ids = $scope.iconTypes[0].pageModel.list.reduce(function (ret, n) {
                n.checked && ret.push(n.id);
                return ret
            }, []);
            $scope.iconTypes[1].pageModel.list.reduce(function (ret, n) {
                n.checked && ret.push(n.id);
                return ret
            }, ids);
            confirm("确认打包下载选中的 " + ids.length + " 个图标吗?",function(){
                try{
                    var elemIF = document.createElement("iframe");
                    elemIF.src = "/icon/downloadZip?ids="+ids.join();
                    elemIF.style.display = "none";
                    document.body.appendChild(elemIF);
                }catch(e){

                }
            })
        }
        $scope.editAll = function(){
            var items = $scope.iconTypes[0].pageModel.list.filter(function (n) {n.checked&&(n.newName = n.name);return n.checked;});
            items.push.apply(items,$scope.iconTypes[1].pageModel.list.filter(function (n) {n.checked&&(n.newName = n.name);return n.checked;}));
            var modal = $uibModal.open({
                animation: false,
                size:'lg',
                templateUrl: 'view/icon/icon.modal.html',
                controller: 'iconEditCtrl'
                ,resolve: {items: function(){return items;}}
            });
            modal.result.then(function () {

            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        }

        function initImage(){
            $scope.iconTypes.forEach(function(n){
                n.pageModel = {};
                find(1,n);
            })
        }

        $scope.shiftType = function(iconType){
            var names = iconType.pageModel.data.reduce(function (ret, n) {
                n.checked && ret.push(n.name);
                return ret
            }, []);
            confirm("确认变更选中的 " + names.length + " 个图标的类型吗?",function(){
            $http.post("../icon/shiftType?iconType="+(iconType.id==1?2:1),names).success(function(resp){
                    if (resp.code == 0) {
                        var otherType = iconType.id==1?$scope.iconTypes[1]:$scope.iconTypes[0];
                        names.forEach(function(name){
                            var toDel = iconType.pageModel.data.find(function(m){return m.name == name});
                            iconType.pageModel.data.splice(iconType.pageModel.data.indexOf(toDel),1);
                            otherType.pageModel.data.splice(0,0,toDel);
                        })
                        iconType.pageModel.totalRecord -= names.length;
                        otherType.pageModel.totalRecord += names.length;
                    } else {
                        alert(resp.msg);
                    }
                })
            })
        }

        $scope.selectType = function(type){
           var curItem = $scope.typeList.find(function(n){return n.active});
           if(curItem && curItem!=type){
               curItem.active = false;
           }
           type.active = true;
            type.pageModel =type.pageModel||{};
           $scope.curType = type;
            if(!type.pageModel.data){
                initImage();
            }
        }

        $scope.editType = function(type){
            type.textCopy = type.text;
            type.edit = true;
            var input = $(event.target).parents("li").children("input");
            $timeout(function(){
                input.select();
            })
        }
        $scope.delType = function(type){
            $http.get("../icon/existImage?folderId="+type.id).success(function(resp){
                if(resp.code ==0){
                    if(resp.data ==1){
                        alert(type.text+"文件夹下存在图标，请清空后再删除！");
                    }else{
                        confirm("确认删除图标分类"+type.text+"？",function(){
                            if($scope.curType == type){
                                delete $scope.curType;
                            }
                            $http.get("../icon/delType?typeId="+type.id).success(function(resp){
                                if(resp.code === 0){
                                    $scope.typeList.splice($scope.typeList.indexOf(type),1);
                                }else{
                                    alert(resp.msg);
                                }
                            })
                        });
                    }
                }
            })
        }
        $scope.saveType = function(form,type){
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            var copy = {};
            angular.extend(copy,type);
            copy.text = type.textCopy;
            $http.post("../icon/saveType",copy).success(function(resp){
                if(resp.code === 0){
                    type.edit = false;
                    type.id = resp.data.id;
                    type.text = resp.data.text;
                }else{
                    alert(resp.msg);
                }
            })
        }
        $scope.cancelEdit = function(type){
            if(type.id){
                type.edit = false;
            }else{
                $scope.typeList.splice($scope.typeList.indexOf(type),1);
            }
        }


    });

    app.controller('iconEditCtrl', function($scope,$http,$uibModalInstance,fac,items) {
        $scope.items = items;
        $scope.save = function (form,items) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            var ids = items.reduce(function(ret,n){ret.push(n.id);return ret},[]);
            var names = items.reduce(function(ret,n){ret.push(n.newName);return ret},[]);
            var scaleIds = items.reduce(function(ret,n){ret.push(n.newScaleId||" ");return ret},[]);

            $http.get("../icon/edit",{params:{ids:ids,names:names,scaleIds:scaleIds}}).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    items.forEach(function(n){n.name = n.newName});
                    items.forEach(function(n){n.scaleId = n.newScaleId});
                    $uibModalInstance.close();
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });
})();